<template>
  <div class="warehouse-receipt-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>入库单管理</h2>
      <p>管理入库单信息，支持查询、导出等操作</p>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="入库时间">
          <el-date-picker
            v-model="searchForm.startTime"
            type="datetime"
            placeholder="开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 180px"
          />
          <span style="margin: 0 8px">至</span>
          <el-date-picker
            v-model="searchForm.endTime"
            type="datetime"
            placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 180px"
          />
        </el-form-item>
        
        <el-form-item label="入库单号">
          <el-input
            v-model="searchForm.entryOrderNumber"
            placeholder="请输入入库单号"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="入库类型">
          <el-input
            v-model="searchForm.entryType"
            placeholder="请输入入库类型"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="创建人">
          <el-input
            v-model="searchForm.createdBy"
            placeholder="请输入创建人"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleExport" :loading="exportLoading">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="table-title">
          <h3>入库单列表</h3>
          <span class="total-count">共 {{ total }} 条记录</span>
        </div>
        <div class="table-actions">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增
          </el-button>
        </div>
      </div>

      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        max-height="400"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="storageId" label="库存ID" width="100" />
        
        <el-table-column prop="entryOrderNumber" label="入库单号" width="150" />
        
        <el-table-column prop="entryType" label="入库类型" width="120" />
        
        <el-table-column prop="entryTime" label="入库时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.entryTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="remarks" label="备注" width="200" show-overflow-tooltip />
        
        <el-table-column prop="createdBy" label="创建人" width="120" />
        
        <el-table-column prop="createdTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createdTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="modifiedBy" label="修改人" width="120" />
        
        <el-table-column prop="modifiedTime" label="修改时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.modifiedTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="isDelete" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isDelete ? 'danger' : 'success'">
              {{ row.isDelete ? '已删除' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 入库单-产品明细 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="table-title">
          <h3>产品明细列表</h3>
          <span class="total-count">共 {{ allProductDetails.length }} 条记录</span>
        </div>

      </div>

      <el-table
        :data="allProductDetails"
        v-loading="detailsLoading"
        stripe
        border
        style="width: 100%"
        max-height="300"
        @selection-change="handleDetailSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="productName" label="*产品名称" width="150" sortable />
        <el-table-column prop="productCode" label="*产品编号" width="150" sortable />
        <el-table-column prop="unit" label="*库存单位" width="100" sortable />
        <el-table-column prop="productSpecification" label="产品规格" width="120" />
        <el-table-column prop="maxInventory" label="最大库存" width="100" sortable />
        <el-table-column prop="minInventory" label="最小库存" width="100" sortable />
        <el-table-column prop="safetyStock" label="安全库存" width="100" sortable />
        <el-table-column prop="num" label="*入库数量" width="120" sortable>
          <template #default="{ row }">
            <el-input-number
              v-model="row.num"
              :min="1"
              :precision="0"
              size="small"
              style="width: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="currentInventory" label="当前库存数" width="120" sortable />
        <el-table-column prop="createdBy" label="创建人" width="120" sortable />
        <el-table-column prop="createdTime" label="创建时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.createdTime) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 明细分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="detailsCurrentPage"
          v-model:page-size="detailsPageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="allProductDetails.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleDetailSizeChange"
          @current-change="handleDetailCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="1200px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="inbound-order-dialog"
    >
      <div class="dialog-content">
        <!-- 基本信息 -->
        <div class="basic-info-section">
          <h3 class="section-title">①基本信息</h3>
          <el-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            label-width="120px"
            class="basic-form"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="入库单号" prop="entryOrderNumber">
                  <el-input
                    v-model="formData.entryOrderNumber"
                    placeholder="请输入,忽略将自动生成"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="入库类型" prop="entryType">
                  <el-select
                    v-model="formData.entryType"
                    placeholder="入库类型"
                    style="width: 100%"
                    clearable
                  >
                    <el-option label="采购入库" value="采购入库" />
                    <el-option label="生产入库" value="生产入库" />
                    <el-option label="退货入库" value="退货入库" />
                    <el-option label="其他入库" value="其他入库" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="入库时间" prop="entryTime">
                  <el-date-picker
                    v-model="formData.entryTime"
                    type="datetime"
                    placeholder="请选择入库时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="创建人" prop="createdBy">
                  <el-input
                    v-model="formData.createdBy"
                    placeholder="请输入创建人"
                    clearable
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="formData.remarks"
                type="textarea"
                :rows="3"
                placeholder="备注"
                clearable
              />
            </el-form-item>
          </el-form>
        </div>

                            <!-- 提示信息 -->
                    <div class="hint-bar">
                      <el-icon><InfoFilled /></el-icon>
                      <span>● 请先选择产品，然后直接点击【入库数量】可以直接进行修改</span>
                    </div>

        <!-- 入库单明细 -->
        <div class="details-section">
          <h3 class="section-title">■入库单明细</h3>
          
          <!-- 操作按钮 -->
          <div class="details-actions">
            <el-button type="primary" @click="handleSelectProduct">
              <el-icon><Plus /></el-icon>
              选择产品
            </el-button>
            <el-button type="danger" @click="handleDeleteSelectedRows" :disabled="selectedDetailRows.length === 0">
              <el-icon><Delete /></el-icon>
              删除行
            </el-button>
            <el-button @click="handleImport">
              <el-icon><Upload /></el-icon>
              导入
            </el-button>
            <el-button @click="handleRefreshDetails">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>

                                                      <!-- 明细表格 -->
                      <el-table
                        :data="orderDetails"
                        v-loading="detailsLoading"
                        stripe
                        border
                        style="width: 100%"
                        max-height="400"
                        @selection-change="handleDetailSelectionChange"
                        :empty-text="'请点击【选择产品】按钮添加产品明细'"
                      >
             <el-table-column type="selection" width="55" />
             
             <el-table-column prop="productName" label="*产品名称" width="150" sortable>
               <template #default="{ row }">
                 <span class="required-field">{{ row.productName }}</span>
               </template>
             </el-table-column>
             
             <el-table-column prop="productCode" label="*产品编号" width="120" sortable>
               <template #default="{ row }">
                 <span class="required-field">{{ row.productCode }}</span>
               </template>
             </el-table-column>
             
             <el-table-column prop="unit" label="*库存单位" width="100">
               <template #default="{ row }">
                 <span class="required-field">{{ row.unit }}</span>
               </template>
             </el-table-column>
             
                                     <el-table-column prop="productSpecification" label="产品规格" width="120" />
                        
                        <el-table-column prop="productAttribute" label="产品属性" width="120" />
                        
                        <el-table-column prop="processRoute" label="工艺路线" width="120" />
                        
                        <el-table-column prop="maxInventory" label="最大库存" width="100" sortable />
                        
                        <el-table-column prop="minInventory" label="最小库存" width="100" sortable />
                        
                        <el-table-column prop="safetyStock" label="安全库存" width="100" sortable />
             
             <el-table-column prop="num" label="*入库数量" width="120" sortable>
               <template #default="{ row }">
                 <el-input-number
                   v-model="row.num"
                   :min="0"
                   :precision="2"
                   size="small"
                   style="width: 100px"
                   @change="handleQuantityChange(row)"
                 />
               </template>
             </el-table-column>
             
             <el-table-column prop="currentInventory" label="当前库存" width="120" />
           </el-table>

                     <!-- 分页 -->
           <div class="pagination-container">
             <el-pagination
               v-model:current-page="detailsCurrentPage"
               v-model:page-size="detailsPageSize"
               :page-sizes="[10, 20, 50, 100]"
               :total="orderDetails.length"
               layout="total, sizes, prev, pager, next, jumper"
               @size-change="handleDetailsSizeChange"
               @current-change="handleDetailsCurrentChange"
             />
           </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">
            <el-icon><Close /></el-icon>
            关闭
          </el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            <el-icon><Check /></el-icon>
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择产品对话框 -->
    <el-dialog
      v-model="productDialogVisible"
      title="选择产品"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="product-dialog-content">
        <!-- 产品搜索 -->
        <div class="product-search">
          <el-input
            v-model="productSearchKeyword"
            placeholder="请输入产品名称或编号搜索"
            style="width: 300px"
            clearable
            @input="handleProductSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

                                     <!-- 产品列表 -->
                    <el-table
                      :data="filteredProducts"
                      v-loading="productsLoading"
                      stripe
                      border
                      style="width: 100%"
                      max-height="400"
                      @selection-change="handleProductSelectionChange"
                    >
                      <el-table-column type="selection" width="55" />
                      <el-table-column prop="productNumber" label="产品编号" width="120" sortable />
                      <el-table-column prop="productName" label="产品名称" width="150" sortable />
                      <el-table-column prop="inventoryUnit" label="库存单位" width="100" />
                      <el-table-column prop="productSpecification" label="产品规格" width="120" />
                      <el-table-column prop="productAttribute" label="产品属性" width="120" />
                      <el-table-column prop="processRoute" label="工艺路线" width="120" />
                      <el-table-column prop="maxInventory" label="最大库存" width="100" sortable />
                      <el-table-column prop="minInventory" label="最小库存" width="100" sortable />
                      <el-table-column prop="safetyInventory" label="安全库存" width="100" sortable />
                      <el-table-column prop="current" label="库存数量" width="100" sortable />
                    </el-table>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="productDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmSelectProducts">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Refresh, Download, Plus, InfoFilled, Delete, Upload, Close, Check } from '@element-plus/icons-vue'
import { 
  getAllInboundOrders, 
  searchInboundOrders, 
  exportInboundOrders, 
  addInboundOrder,
  updateInboundOrder,
  deleteInboundOrder,
  getProducts,
  getInboundOrderDetails,
  addInboundOrderDetail,
  updateInboundOrderDetail,
  deleteInboundOrderDetail,
  batchAddInboundOrderDetails,
  saveInboundOrderDetails,
  type InboundOrder, 
  type SearchParams,
  type AddInboundOrderParams,
  type Product,
  type InboundOrderDetail
} from '@/api/warehouseReceipt'
import { exportToCSVInboundOrder, exportToExcelInboundOrder } from '@/utils/excelExport'

// 响应式数据
const loading = ref(false)
const exportLoading = ref(false)
const submitLoading = ref(false)
const detailsLoading = ref(false)
const productsLoading = ref(false)
const tableData = ref<InboundOrder[]>([])
const selectedRows = ref<InboundOrder[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const productDialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()

// 产品相关
const products = ref<Product[]>([])
const filteredProducts = ref<Product[]>([])
const selectedProducts = ref<Product[]>([])
const productSearchKeyword = ref('')

// 明细相关
const selectedDetailRows = ref<InboundOrderDetail[]>([])
const detailsCurrentPage = ref(1)
const detailsPageSize = ref(100)
const allProductDetails = ref<InboundOrderDetail[]>([])

// 搜索表单
const searchForm = reactive<SearchParams>({
  startTime: '',
  endTime: '',
  entryOrderNumber: '',
  entryType: '',
  createdBy: ''
})

// 表单数据
const formData = reactive({
  storageId: 1,
  entryOrderNumber: '',
  entryType: '',
  entryTime: '',
  remarks: '',
  createdTime: '',
  createdBy: '',
  modifiedBy: '',
  modifiedTime: '',
  isDelete: false
})

// 明细数据（单独管理）
const orderDetails = ref<InboundOrderDetail[]>([])

// 表单验证规则
const formRules: FormRules = {
  entryOrderNumber: [
    { required: false, message: '入库单号可选填', trigger: 'blur' }
  ],
  entryType: [
    { required: true, message: '请选择入库类型', trigger: 'change' }
  ],
  entryTime: [
    { required: true, message: '请选择入库时间', trigger: 'change' }
  ],
  createdBy: [
    { required: true, message: '请输入创建人', trigger: 'blur' }
  ]
}

// 计算属性：是否有搜索条件
const hasSearchConditions = computed(() => {
  return searchForm.startTime || searchForm.endTime || searchForm.entryOrderNumber || searchForm.entryType || searchForm.createdBy
})

const dialogTitle = computed(() => {
  return isEdit.value ? '编辑入库单' : '新增入库单'
})

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 生成入库单号（后端要求必填）
const generateEntryOrderNumber = (): string => {
  const now: Date = new Date()
  const pad = (num: number): string => num.toString().padStart(2, '0')
  const year = now.getFullYear()
  const month = pad(now.getMonth() + 1)
  const day = pad(now.getDate())
  const hour = pad(now.getHours())
  const minute = pad(now.getMinutes())
  const second = pad(now.getSeconds())
  const randomSuffix = Math.floor(100 + Math.random() * 900) // 3位随机数
  return `RK${year}${month}${day}${hour}${minute}${second}${randomSuffix}`
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    let response
    if (hasSearchConditions.value) {
      response = await searchInboundOrders(searchForm)
    } else {
      response = await getAllInboundOrders()
    }
    
    if (response.code === 200) {
      tableData.value = response.data
      total.value = response.data.length
      ElMessage.success('数据加载成功')
    } else {
      ElMessage.error(response.msg || '数据加载失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 获取产品列表
const fetchProducts = async () => {
  productsLoading.value = true
  detailsLoading.value = true
  try {
    const response = await getProducts()
    if (response.code === 200) {
      products.value = response.data
      filteredProducts.value = response.data
      
      // 同时更新产品明细表格的数据
      allProductDetails.value = response.data.map((product: Product) => ({
        productId: product.productId,
        productName: product.productName,
        productCode: product.productNumber,
        productSpecification: product.productSpecification,
        unit: product.inventoryUnit,
        productAttribute: product.productAttribute || '',
        processRoute: product.processRoute || '',
        maxInventory: product.maxInventory,
        minInventory: product.minInventory,
        safetyStock: product.safetyInventory,
        currentInventory: product.current,
        num: product.num || 0,
        createdBy: product.createdBy || 'admin',
        createdTime: product.createdTime || new Date().toISOString()
      }))
    } else {
      ElMessage.error(response.msg || '获取产品列表失败')
    }
  } catch (error) {
    console.error('获取产品列表失败:', error)
    ElMessage.error('获取产品列表失败')
  } finally {
    productsLoading.value = false
    detailsLoading.value = false
  }
}

// 搜索
const handleSearch = async () => {
  currentPage.value = 1
  await fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    startTime: '',
    endTime: '',
    entryOrderNumber: '',
    entryType: '',
    createdBy: ''
  })
  currentPage.value = 1
  fetchData()
}

// 导出
const handleExport = async () => {
  exportLoading.value = true
  try {
    // 尝试后端导出
    try {
      const blob = await exportInboundOrders(searchForm)
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `入库单数据_${new Date().toISOString().slice(0, 10)}.xlsx`
      link.click()
      window.URL.revokeObjectURL(url)
      ElMessage.success('导出成功')
      return
    } catch (backendError) {
      console.warn('后端导出失败，使用前端导出:', backendError)
    }
    
    // 前端导出作为备选
    const dataToExport = hasSearchConditions.value ? tableData.value : tableData.value
    const success = await exportToExcelInboundOrder(dataToExport, `入库单数据_${new Date().toISOString().slice(0, 10)}`)
    
    if (success) {
      ElMessage.success('导出成功')
    } else {
      ElMessage.error('导出失败')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  
  // 设置默认值
  formData.storageId = 1
  formData.entryOrderNumber = generateEntryOrderNumber()
  formData.entryType = ''
  formData.entryTime = new Date().toISOString()
  formData.remarks = ''
  formData.createdBy = 'admin' // 设置默认创建人
  formData.modifiedBy = 'admin' // 设置默认修改人
  
  // 清空明细数据，等待用户选择真实产品
  orderDetails.value = []
  
  dialogVisible.value = true
  fetchProducts()
}

// 编辑 - 最终修复版本
const handleEdit = async (row: InboundOrder) => {
  // 设置基本信息
  isEdit.value = true
  resetForm()
  Object.assign(formData, row)
  dialogVisible.value = true
  fetchProducts()
  
  // 获取明细数据
  if (row.entryOrderNumber) {
    detailsLoading.value = true
    
    try {
      const response = await getInboundOrderDetails(row.entryOrderNumber)
      
      // 直接使用API返回的数据，不做复杂转换
      if (response && response.code === 200) {
        orderDetails.value = response.data || []
        
        if (orderDetails.value.length > 0) {
          ElMessage.success(`成功加载 ${orderDetails.value.length} 条产品明细`)
        } else {
          ElMessage.info('该入库单暂无产品明细')
        }
      } else {
        ElMessage.error('获取明细数据失败')
        orderDetails.value = []
      }
      
    } catch (error) {
      console.error('获取明细失败:', error)
      ElMessage.error('获取明细数据失败')
      orderDetails.value = []
    } finally {
      detailsLoading.value = false
    }
  } else {
    ElMessage.warning('入库单号为空')
    orderDetails.value = []
  }
}

// 删除
const handleDelete = async (row: InboundOrder) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除入库单 "${row.entryOrderNumber}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteInboundOrder(row.storageId)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 选择产品
const handleSelectProduct = () => {
  // 确保产品列表已加载
  if (products.value.length === 0) {
    fetchProducts()
  }
  
  productDialogVisible.value = true
  selectedProducts.value = []
  productSearchKeyword.value = ''
  filteredProducts.value = products.value
}

// 删除选中的明细行
const handleDeleteSelectedRows = () => {
  if (selectedDetailRows.value.length === 0) {
    ElMessage.warning('请选择要删除的行')
    return
  }
  
  const selectedIds = selectedDetailRows.value.map((row: InboundOrderDetail) => row.productId)
  orderDetails.value = orderDetails.value.filter((detail: InboundOrderDetail) => !selectedIds.includes(detail.productId))
  selectedDetailRows.value = []
  ElMessage.success('删除成功')
}

// 导入功能
const handleImport = () => {
  ElMessage.info('导入功能开发中...')
}

// 刷新明细
const handleRefreshDetails = () => {
  // 清空测试数据
  orderDetails.value = []
  fetchProducts()
  ElMessage.success('刷新成功')
}

// 明细选择变化
const handleDetailSelectionChange = (selection: InboundOrderDetail[]) => {
  selectedDetailRows.value = selection
}

// 产品选择变化
const handleProductSelectionChange = (selection: Product[]) => {
  selectedProducts.value = selection
}

// 产品搜索
const handleProductSearch = () => {
  if (!productSearchKeyword.value) {
    filteredProducts.value = products.value
  } else {
    filteredProducts.value = products.value.filter(product => 
      product.productName.includes(productSearchKeyword.value) ||
      product.productNumber.includes(productSearchKeyword.value)
    )
  }
}

// 确认选择产品
const handleConfirmSelectProducts = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择产品')
    return
  }
  
  // 添加选中的产品到明细
  selectedProducts.value.forEach(product => {
    // 检查是否已存在
    const exists = orderDetails.value.some((detail: InboundOrderDetail) => detail.productId === product.productId)
    if (!exists) {
      const newDetail = {
        productId: product.productId,
        productName: product.productName,
        productCode: product.productNumber,
        productSpecification: product.productSpecification,
        unit: product.inventoryUnit,
        productAttribute: product.productAttribute || '',
        processRoute: product.processRoute || '',
        maxInventory: product.maxInventory,
        minInventory: product.minInventory,
        safetyStock: product.safetyInventory,
        currentInventory: product.current,
        num: 1, // 设置默认入库数量为1
        createdBy: formData.createdBy || 'admin',
        createdTime: new Date().toISOString()
      }
      orderDetails.value.push(newDetail)
      console.log('添加新产品明细:', newDetail)
    }
  })
  
  console.log('当前orderDetails:', orderDetails.value)
  
  // 强制触发响应式更新
  orderDetails.value = [...orderDetails.value]
  
  productDialogVisible.value = false
  selectedProducts.value = []
  ElMessage.success('添加产品成功')
}

// 数量变化
const handleQuantityChange = (row: InboundOrderDetail) => {
  console.log('数量变化:', row.productName, row.num)
  console.log('当前行数据:', row)
}

// 明细分页大小变化
const handleDetailsSizeChange = (size: number) => {
  detailsPageSize.value = size
  detailsCurrentPage.value = 1
}

// 明细当前页变化
const handleDetailsCurrentChange = (page: number) => {
  detailsCurrentPage.value = page
}

// 添加产品（打开产品选择对话框）
const handleAddProduct = () => {
  // 只有在编辑入库单时才能添加产品
  if (!dialogVisible.value) {
    ElMessage.warning('请先选择或创建入库单')
    return
  }
  
  // 确保产品列表已加载
  if (products.value.length === 0) {
    fetchProducts()
  }
  
  productDialogVisible.value = true
  selectedProducts.value = []
  productSearchKeyword.value = ''
  filteredProducts.value = products.value
}

// 删除选中的明细
const handleDeleteSelectedDetails = () => {
  if (selectedDetailRows.value.length === 0) {
    ElMessage.warning('请选择要删除的产品')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedDetailRows.value.length} 个产品吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const selectedIds = selectedDetailRows.value.map(row => row.productId)
    allProductDetails.value = allProductDetails.value.filter(detail => !selectedIds.includes(detail.productId))
    selectedDetailRows.value = []
    ElMessage.success('删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

// 明细分页大小变化（别名）
const handleDetailSizeChange = handleDetailsSizeChange

// 明细当前页变化（别名）
const handleDetailCurrentChange = handleDetailsCurrentChange

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 验证明细数据
    if (orderDetails.value.length === 0) {
      ElMessage.warning('请至少添加一个产品明细')
      return
    }
    
    // 验证入库数量
    const invalidDetails = orderDetails.value.filter(detail => !detail.num || detail.num <= 0)
    if (invalidDetails.length > 0) {
      ElMessage.warning(`以下产品的入库数量必须大于0：${invalidDetails.map(d => d.productName).join('、')}`)
      return
    }
    
    submitLoading.value = true
    
    // 设置时间字段 - 使用ISO格式
    const now = new Date().toISOString()
    if (!isEdit.value) {
      formData.createdTime = now
      formData.modifiedTime = now
    } else {
      formData.modifiedTime = now
    }
    
    // 确保必填：入库单号
    if (!formData.entryOrderNumber) {
      formData.entryOrderNumber = generateEntryOrderNumber()
    }
    
    console.log('表单数据中的入库单号:', formData.entryOrderNumber)
    
    // 准备提交数据（直接发送，不包装dto）
    const submitData = {
      storageId: formData.storageId,
      entryOrderNumber: formData.entryOrderNumber,
      entryType: formData.entryType,
      entryTime: formData.entryTime,
      remarks: formData.remarks,
      createdTime: formData.createdTime,
      createdBy: formData.createdBy,
      modifiedBy: formData.modifiedBy,
      modifiedTime: formData.modifiedTime,
      isDelete: formData.isDelete
    }
    
    // 添加调试日志
    console.log('提交的表单数据:', submitData)
    
    let response
    if (isEdit.value) {
      response = await updateInboundOrder(submitData as InboundOrder)
    } else {
      response = await addInboundOrder(submitData as AddInboundOrderParams)
    }
    
    if (response.code === 200) {
      // 主表保存成功，继续保存明细
      if (orderDetails.value.length > 0) {
        try {
          // 准备明细数据 - 修复数据映射问题，确保入库单号正确关联
          const detailsToSave = orderDetails.value.map(detail => ({
            // 记录ID - 编辑模式必须提供
            id: (detail.id ?? detail.productDetailId ?? null),
            
            // 入库单号 - 确保字段名正确，这是关键的关联字段
            entryOrderNumber: formData.entryOrderNumber,
            EntryOrderNumber: formData.entryOrderNumber, // 兼容大写开头
            
            // 产品基本信息
            productId: detail.productId,
            productName: detail.productName,
            productNumber: detail.productCode, // 使用productCode字段
            productCode: detail.productCode, // 兼容字段名
            productSpecification: detail.productSpecification || '',
            
            // 库存信息
            inventoryUnit: detail.unit, // 使用unit字段
            unit: detail.unit, // 兼容字段名
            maxInventory: detail.maxInventory || 0,
            minInventory: detail.minInventory || 0,
            safetyInventory: detail.safetyStock, // 使用safetyStock字段
            safetyStock: detail.safetyStock, // 兼容字段名
            
            // 当前库存和入库数量
            current: detail.currentInventory, // 使用currentInventory字段
            currentInventory: detail.currentInventory, // 兼容字段名
            inventoryQuantity: Math.max(detail.num || 0, 1), // 入库数量
            num: Math.max(detail.num || 0, 1), // 兼容字段名
            
            // 其他字段
            productAttribute: detail.productAttribute || '',
            processRoute: detail.processRoute || '',
            
            // 系统字段
            isDelete: false,
            createdBy: formData.createdBy || 'admin',
            modifiedBy: formData.modifiedBy || 'admin',
            createdTime: new Date().toISOString(),
            modifiedTime: new Date().toISOString()
          }))
          
          console.log('准备保存的明细数据:', detailsToSave)
          console.log('入库单号:', formData.entryOrderNumber)
          
          // 根据是否为编辑模式选择保存方式
          if (isEdit.value) {
            // 编辑模式：逐个更新明细
            console.log('编辑模式：逐个更新产品明细')
            let updateSuccessCount = 0
            let updateFailCount = 0
            
            for (const detail of detailsToSave) {
              try {
                // 如果没有ID，则改为新增该明细，避免阻塞整体保存
                if (detail.id === null || detail.id === undefined) {
                  console.warn('发现无ID明细，转新增:', detail.productName)
                  try {
                    const addResp = await addInboundOrderDetail({
                      entryOrderNumber: detail.entryOrderNumber ?? formData.entryOrderNumber,
                      productId: detail.productId,
                      productName: detail.productName,
                      productNumber: detail.productNumber ?? detail.productCode,
                      productSpecification: detail.productSpecification ?? '',
                      inventoryUnit: detail.inventoryUnit ?? detail.unit ?? '',
                      maxInventory: detail.maxInventory ?? 0,
                      minInventory: detail.minInventory ?? 0,
                      safetyInventory: detail.safetyInventory ?? detail.safetyStock ?? 0,
                      current: detail.current ?? detail.currentInventory ?? 0,
                      num: detail.num ?? 1,
                      isDelete: false,
                      createdBy: formData.createdBy || 'admin',
                      modifiedBy: formData.modifiedBy || 'admin',
                      createdTime: new Date().toISOString(),
                      modifiedTime: new Date().toISOString()
                    })
                    if (addResp.code === 200) {
                      updateSuccessCount++
                      console.log('转新增明细成功:', detail.productName)
                    } else {
                      updateFailCount++
                    }
                  } catch (e) {
                    updateFailCount++
                  }
                  continue
                }
                
                console.log('准备更新明细:', {
                  id: detail.id,
                  productName: detail.productName,
                  productId: detail.productId
                })
                
                const updateResp = await updateInboundOrderDetail(detail)
                if (updateResp.code === 200) {
                  updateSuccessCount++
                  console.log('更新明细成功:', detail.productName)
                } else {
                  updateFailCount++
                  console.error('更新明细失败:', detail.productName, updateResp.msg)
                }
              } catch (error) {
                updateFailCount++
                console.error('更新明细异常:', detail.productName, error)
              }
            }
            
            if (updateFailCount === 0) {
              ElMessage.success('更新成功')
            } else if (updateSuccessCount > 0) {
              ElMessage.warning(`部分明细更新成功：成功 ${updateSuccessCount} 条，失败 ${updateFailCount} 条`)
            } else {
              ElMessage.warning('主表保存成功，但明细更新失败')
            }
          } else {
            // 新增模式：批量保存明细
            console.log('🆕 新增模式：批量保存产品明细')
            console.log('📋 准备保存的入库单号:', formData.entryOrderNumber)
            console.log('📦 准备保存的明细数量:', detailsToSave.length)
            
            try {
              const detailResp = await saveInboundOrderDetails(
                formData.entryOrderNumber, 
                detailsToSave,
                formData.createdBy,
                formData.modifiedBy
              )
              
              console.log('💾 明细保存响应:', detailResp)
              
              if (detailResp.code === 200) {
                const stats = detailResp.data as any
                console.log('📊 保存统计:', stats)
                
                if (stats && stats.failCount === 0) {
                  ElMessage.success(`新增成功！已保存 ${stats.okCount} 条产品明细`)
                } else if (stats && stats.okCount > 0) {
                  ElMessage.warning(`部分明细保存成功：成功 ${stats.okCount} 条，失败 ${stats.failCount} 条`)
                } else {
                  ElMessage.warning('主表保存成功，但明细保存失败，请检查产品数据')
                }
              } else {
                console.error('❌ 明细保存失败:', detailResp.msg)
                ElMessage.warning(`主表保存成功，但明细保存失败: ${detailResp.msg}`)
              }
            } catch (detailSaveError) {
              console.error('💥 明细保存异常:', detailSaveError)
              ElMessage.warning('主表保存成功，但明细保存时发生异常，请检查网络连接')
            }
          }
        } catch (detailError) {
          console.error('保存明细失败:', detailError)
          ElMessage.warning('主表保存成功，但明细保存失败')
        }
      } else {
        ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
      }
      
      dialogVisible.value = false
      // 重新获取数据，确保列表数据是最新的
      await fetchData()
    } else {
      ElMessage.error(response.msg || (isEdit.value ? '更新失败' : '新增失败'))
    }
  } catch (error: any) {
    console.error('提交失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      console.error('错误状态:', error.response.status)
    }
    ElMessage.error(isEdit.value ? '更新失败' : '新增失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    storageId: 1,
    entryOrderNumber: '',
    entryType: '',
    entryTime: '',
    remarks: '',
    createdTime: '',
    createdBy: '',
    modifiedBy: '',
    modifiedTime: '',
    isDelete: false
  })
  
  // 重置明细数据
  orderDetails.value = []
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 选择变化
const handleSelectionChange = (selection: InboundOrder[]) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchData()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchData()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
  fetchProducts() // 同时获取产品明细数据
})
</script>

<style scoped>
.warehouse-receipt-container {
  padding: 20px;
  background: #f5f5f5;
  height: 100vh;
  overflow-y: auto;
  overflow-x: hidden;
}

/* 自定义滚动条样式 */
.warehouse-receipt-container::-webkit-scrollbar {
  width: 8px;
}

.warehouse-receipt-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.warehouse-receipt-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.warehouse-receipt-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

/* 产品明细表格特殊样式 */
.table-card:nth-child(3) {
  margin-top: 30px;
}

.table-card:nth-child(3) .table-title h3 {
  color: #409eff;
}

.table-card:nth-child(3) .el-table {
  border: 2px solid #e4e7ed;
}

.table-card:nth-child(3) .el-table th {
  background-color: #f0f9ff;
  color: #1e40af;
  font-weight: 600;
}

.table-card:nth-child(3) .el-table .el-input-number {
  width: 100px;
}

.table-card:nth-child(3) .el-table .el-input-number .el-input__inner {
  text-align: center;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-title h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.total-count {
  color: #909399;
  font-size: 14px;
}

.table-actions {
  display: flex;
  gap: 12px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.details-section .pagination-container {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.dialog-footer {
  text-align: right;
}

/* 新增入库单对话框样式 */
.inbound-order-dialog {
  .el-dialog__body {
    padding: 0;
  }
}

.dialog-content {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.section-title {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  border-left: 4px solid #409eff;
  padding-left: 12px;
}

.basic-info-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.basic-form {
  .el-form-item {
    margin-bottom: 16px;
  }
}

.hint-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: #fff7e6;
  border: 1px solid #ffd591;
  border-radius: 6px;
  margin-bottom: 20px;
  color: #d46b08;
  font-size: 14px;
  font-weight: 500;
}

.hint-bar .el-icon {
  color: #fa8c16;
  font-size: 16px;
}

.hint-bar span {
  line-height: 1.4;
}

.details-section {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.details-section .el-table {
  margin-top: 16px;
}

.details-section .el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.details-section .el-table .el-table__cell {
  padding: 8px 0;
}

.details-section .el-input-number {
  width: 100px;
}

.details-section .el-input-number .el-input__inner {
  text-align: center;
}

.details-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.details-actions .el-button {
  padding: 8px 16px;
  font-size: 14px;
}

.details-actions .el-button .el-icon {
  margin-right: 4px;
}

.required-field {
  font-weight: 500;
}

.product-dialog-content {
  .product-search {
    margin-bottom: 16px;
    display: flex;
    justify-content: flex-end;
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .warehouse-receipt-container {
    padding: 15px;
  }
  
  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .dialog-content {
    padding: 15px;
  }
  
  .basic-info-section,
  .details-section {
    padding: 15px;
  }
}

@media (max-width: 768px) {
  .warehouse-receipt-container {
    padding: 10px;
  }
  
  .page-header h2 {
    font-size: 20px;
  }
  
  .table-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .dialog-content {
    padding: 10px;
  }
  
  .basic-info-section,
  .details-section {
    padding: 10px;
  }
  
  .details-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .hint-bar {
    flex-direction: column;
    text-align: center;
    gap: 4px;
  }
}
</style>
